package com.dream.myqiyi.ui;

import java.util.ArrayList;
import java.util.List;

import com.dream.myqiyi.Global;
import com.dream.myqiyi.R;
import com.dream.myqiyi.AsyncImageLoader.ImageCallback;
import com.dream.myqiyi.dao.NoteModel;
import com.dream.myqiyi.service.ApplicationContext;
import com.dream.myqiyi.service.NoteManager;

import android.app.Activity;
import android.graphics.drawable.Drawable;
import android.os.AsyncTask;
import android.os.Bundle;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AbsListView;
import android.widget.BaseAdapter;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;
import android.widget.AbsListView.OnScrollListener;

public class FavoriteActivity extends Activity {
	private ListView lvNotes;			// note listview 对象
	private LinearLayout llLoading;		// 控制显示正在加载的progress
	private List<NoteModel> notes;		// note 数据
	private boolean isScrolling = false;// 是否正在滚动 
	private SubjectListAdapter adapter;	// 数据适配器
	private boolean isLoading = false;	// 是否正在加载
	
	//private MyLetterListView letterListView;
    //private static final String NAME = "name", NUMBER = "number", SORT_KEY = "sort_key";
    //private HashMap<String, Integer> alphaIndexer;//存放存在的汉语拼音首字母和与之对应的列表位置
    //private String[] sections;//存放存在的汉语拼音首字母

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.main_tab_favorites);
		
		lvNotes = (ListView)this.findViewById(R.id.lv_all_notes);
		llLoading = (LinearLayout) this.findViewById(R.id.ll_notes_loading);
		notes = new ArrayList<NoteModel>();
		adapter = new SubjectListAdapter();
		
		//letterListView = (MyLetterListView)this.findViewById(R.id.MyLetterListView01);
		//letterListView.setOnTouchingLetterChangedListener(new LetterListViewListener());
		
		//第一次加载数据
		getData();
		
		//lv_main_books的setOnScrollListener主要是实现里面的方法进而判断是否处于滚动和是否已经滚动到最底
		lvNotes.setOnScrollListener(new OnScrollListener() {
			//三种不同状态
			@Override
			public void onScrollStateChanged(AbsListView view, int scrollState) {
				switch (scrollState) {
				case OnScrollListener.SCROLL_STATE_FLING:
					isScrolling = true;
					break;
				case OnScrollListener.SCROLL_STATE_IDLE:
					isScrolling = false;
					int startindex = lvNotes.getFirstVisiblePosition();
					int count = lvNotes.getChildCount();
					for (int i = 0; i < count; i++) {
						int currentpostion = startindex + i;
						final NoteModel note = (NoteModel) lvNotes.getItemAtPosition(currentpostion);
						final View viewChild = lvNotes.getChildAt(i);
						ImageView ivNoteImage = (ImageView) viewChild.findViewById(R.id.note_image_iv);
						Drawable drawable = Global.asyncImageLoader.loadDrawable(note.attributeSourceUrl, 150, 150,
								new ImageCallback() {
									public void imageLoaded(Drawable imageDrawable, String imageUrl) {
										ImageView imageViewByTag = (ImageView)lvNotes.findViewWithTag(imageUrl);
										if (imageViewByTag != null) {
											imageViewByTag.setImageDrawable(imageDrawable);
										}
									}
								});

						if (drawable != null) {
							ivNoteImage.setImageDrawable(drawable);
						} else {
							ivNoteImage.setImageResource(R.drawable.ic_launcher);
						}
					}
					break;
				case OnScrollListener.SCROLL_STATE_TOUCH_SCROLL:
					isScrolling = true;
					break;
				}
			}
			//是否已到最底
			@Override
			public void onScroll(AbsListView view, int firstVisibleItem,
					int visibleItemCount, int totalItemCount) {
				 if (totalItemCount <= 0){
                     return;
             }
				if(firstVisibleItem+visibleItemCount == totalItemCount ){
					if(isLoading){
						return;
					}
					new AsyncTask<Void, String, List<NoteModel>>() {
						protected List<NoteModel> doInBackground(Void... params) {
							List<NoteModel> listNewNotes = null;
								//listNewNotes = NewBookDao.getAllNewBooks();

							return listNewNotes;
						}

						protected void onPreExecute() {
							llLoading.setVisibility(View.VISIBLE);
							isLoading = true;
							super.onPreExecute();
						}

						protected void onPostExecute(List<NoteModel> result) {
							llLoading.setVisibility(View.GONE);
							System.out.println("更新adapter");
							isLoading = false;

							if (result != null) {
								notes.addAll(result);
								adapter.notifyDataSetChanged();
								System.out.println("一共有" + notes.size() + "本书");
								super.onPostExecute(result);
							}
						}

						protected void onProgressUpdate(String... values) {
							Toast.makeText(FavoriteActivity.this, values[0], Toast.LENGTH_SHORT).show();
							super.onProgressUpdate(values);
						}

					}.execute();
				}
				
			}
		});
	}
	
	//获取第一次显示的数据
	private void getData() {
		new AsyncTask<Void, String, List<NoteModel>>() {
			protected List<NoteModel> doInBackground(Void... params) {
				List<NoteModel> listNewNotes = null;
				try {
					NoteManager noteMgr = (NoteManager)ApplicationContext.getSingleton().getBean("NoteManager");
					if (noteMgr != null) {
						listNewNotes = noteMgr.getAllFavorite();
					}

					//listNewNotes = NewBookDao.getAllNewBooks();

				} catch (Exception e) {
					publishProgress("获取新书失败,请稍后再试。。。");
					e.printStackTrace();
				}
				return listNewNotes;
			}

			protected void onPreExecute() {
				llLoading.setVisibility(View.VISIBLE);
				super.onPreExecute();
			}

			protected void onPostExecute(List<NoteModel> result) {
				llLoading.setVisibility(View.GONE);
				lvNotes.setAdapter(adapter);
				
				notes.clear();
				if (result != null) {
					notes.addAll(result);
					System.out.println("一共有" + notes.size() + "本书");
					super.onPostExecute(result);
				}
			}

			protected void onProgressUpdate(String... values) {
				Toast.makeText(FavoriteActivity.this, values[0], Toast.LENGTH_SHORT).show();
				super.onProgressUpdate(values);
			}

		}.execute();
	}
	
	private class SubjectListAdapter extends BaseAdapter{
		
		@Override
		public int getCount() {
			return notes.size();
		}

		@Override
		public Object getItem(int position) {
			// TODO Auto-generated method stub
			return notes.get(position);
		}

		@Override
		public long getItemId(int position) {
			// TODO Auto-generated method stub
			return position;
		}

		@Override
		public View getView(int position, View convertView, ViewGroup parent) {
			
			View view = null;
			NoteViewCache viewCache;
			ViewHolder viewHolder = null;
			if (convertView == null) {
				viewHolder = new ViewHolder();
				view = View.inflate(FavoriteActivity.this, R.layout.list_child_item_note, null);
				viewCache = new NoteViewCache(view);
				view.setTag(R.id.tag_first,viewCache);
//				viewHolder.tv_name = (TextView) view.findViewById(R.id.tv_name);
//				viewHolder.tv_message = (TextView) view.findViewById(R.id.tv_message);
//				viewHolder.tv_synopsis = (TextView) view.findViewById(R.id.tv_synopsis);
				view.setTag(R.id.tag_second,viewHolder);
			} else {
				view = convertView;
				viewHolder = (ViewHolder) view.getTag(R.id.tag_second);
				viewCache = (NoteViewCache) view.getTag(R.id.tag_first);
			}
			NoteModel newNote = notes.get(position);
//			viewHolder.tv_name.setText(newBook.getBookName());
//			viewHolder.tv_message.setText(newBook.getBookMessage());
//			viewHolder.tv_synopsis.setText(newBook.getBookSynopsis());
			String imgUrl = newNote.attributeSourceUrl;
			ImageView imgBook = viewCache.getImageView();
			imgBook.setTag(imgUrl);
			if (isScrolling){//滑动式加载本地的假图片
				imgBook.setImageResource(R.drawable.ic_launcher);
			}else{//静止时下载网上的真图片
				Drawable drawable = Global.asyncImageLoader.loadDrawable(imgUrl, 150, 150,
						new ImageCallback() {
							public void imageLoaded(Drawable imageDrawable,
									String imageUrl) {
								ImageView imageViewByTag = (ImageView) lvNotes.findViewWithTag(imageUrl);
								if (imageViewByTag != null) {
									imageViewByTag.setImageDrawable(imageDrawable);
								}
							}
						});

				if (drawable != null) {
					imgBook.setImageDrawable(drawable);
				} else {
					imgBook.setImageResource(R.drawable.ic_launcher);
				}
			}
			
			return view;
		}
		
	}
	static class ViewHolder {
		ImageView iv_icon;
		TextView tv_name;
		TextView tv_message;
		TextView tv_synopsis;

	}

}
